//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.jn.erp.web.api.student.utils;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jn.erp.security.sysservice.enums.BaseEnum;
import com.jn.erp.web.api.common.entity.TLabel;
import com.jn.erp.web.api.common.service.TLabelService;
import com.jn.erp.web.api.course.entity.TCourse;
import com.jn.erp.web.api.course.entity.TCoursePrice;
import com.jn.erp.web.api.course.service.TCoursePriceService;
import com.jn.erp.web.api.course.service.TCourseService;
import com.jn.erp.web.api.institution.entity.vo.EmployeeVo;
import com.jn.erp.web.api.institution.service.EmployeeService;
import com.jn.erp.web.api.student.entity.Student;
import com.jn.erp.web.api.student.entity.StudentClass;
import com.jn.erp.web.api.student.entity.StudentClassGrade;
import com.jn.erp.web.api.student.service.ClassGradeService;
import com.jn.erp.web.api.student.service.StudentService;
import org.apache.poi.hssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ImportExportService {
    private static final Logger log = LoggerFactory.getLogger(ImportExportService.class);

    @Autowired
    private TCourseService tCourseService;

    @Autowired
    private TLabelService labelService;

    @Autowired
   private ClassGradeService classGradeService;

    @Autowired
   private StudentService studentService;



    @Autowired
    private TCoursePriceService coursePriceService;

    @Autowired
    private com.jn.erp.web.api.student.service.ClassService classService;

    @Autowired
    private EmployeeService emloyeeService;

    public ImportExportService() {
    }

    public <T> void exportExcel(Map<String, String> headerMap, List<T> dataList, String titleName) {
        if (dataList != null && dataList.size() != 0) {
            titleName = titleName + LocalDate.now().toString();
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletResponse response = servletRequestAttributes.getResponse();
            if (response == null) {
                throw new BizException("响应错误");
            } else {
                ExcelWriter writer = ExcelUtil.getWriter();
                Iterator var7 = headerMap.keySet().iterator();

                while (var7.hasNext()) {
                    String key = (String) var7.next();
                    writer.addHeaderAlias(key, (String) headerMap.get(key));
                }

                ArrayList data = new ArrayList();

                try {
                    Iterator var16 = dataList.iterator();

                    while (var16.hasNext()) {
                        T item = (T) var16.next();
                        Map<String, Object> newMap = new LinkedHashMap();
                        Map<String, Object> itemMap = objectToMap(item);
                        Iterator var12 = headerMap.keySet().iterator();

                        while (var12.hasNext()) {
                            String key = (String) var12.next();
                            newMap.put(key, itemMap.get(key));
                        }

                        data.add(newMap);
                    }
                } catch (IllegalAccessException var14) {
                    writer.close();
                    throw new BizException("数据映射错误:" + var14.getMessage());
                }

                writer.merge(headerMap.size() - 1, titleName);
                writer.write(data, true);
                this.handleExport(response, writer, titleName);
            }
        } else {
            throw new BizException("导出数据为空");
        }
    }

    private static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap();
        Class<?> clazz = obj.getClass();
        Field[] var3 = clazz.getDeclaredFields();
        int var4 = var3.length;

        for (int var5 = 0; var5 < var4; ++var5) {
            Field field = var3[var5];
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = field.get(obj);
            if (value instanceof BaseEnum) {
                map.put(fieldName, ((BaseEnum) value).getName());
            } else {
                map.put(fieldName, value == null ? "" : String.valueOf(value));
            }
        }

        return map;
    }

    public void exportExcel(HttpServletResponse response, Map<String, String> headerMap, List<Map<String, Object>> exampleList, String titleName) {
        titleName = titleName + LocalDate.now().toString();
        ExcelWriter writer = ExcelUtil.getWriter();
        Map<String, Object> emptyRow = new LinkedHashMap();
        Iterator var7 = headerMap.keySet().iterator();

        while (var7.hasNext()) {
            String key = (String) var7.next();
            writer.addHeaderAlias(key, (String) headerMap.get(key));
            emptyRow.put(key, "");
        }

        writer.merge(headerMap.size() - 1, titleName);
        if (exampleList == null) {
            exampleList = new ArrayList();
            ((List) exampleList).add(emptyRow);
        }

        writer.write((Iterable) exampleList, true);
        this.handleExport(response, writer, titleName);
    }

    private void handleExport(HttpServletResponse response, ExcelWriter writer, String titleName) {
        response.setContentType("application/vnd.ms-excel;charset=utf-8");

        try {
            String name = URLEncoder.encode(titleName, StandardCharsets.UTF_8.toString());
            response.setHeader("Content-Disposition", "attachment;filename=" + name + ".xls");
        } catch (UnsupportedEncodingException var6) {
            log.error("URL转码异常：" + var6.getMessage());
        }

        try {
            writer.flush(response.getOutputStream(), true);
            writer.close();
        } catch (Exception var5) {
            log.error("Excel导出IO异常：" + var5.getMessage());
        }

    }

    public List<Map<String, Object>> importExcel(MultipartFile file, Map<String, String> headerMap) {
        String fileName = file.getOriginalFilename();
        if (!CommonUtil.checkFileExt(fileName, ".xls,.xlsx")) {
            log.error("请上传扩展名为.xls或.xlsx的文件");
            throw new BizException("请上传扩展名为.xls或.xlsx的文件");
        } else {
            ExcelReader reader;
            try {
                InputStream inputStream = file.getResource().getInputStream();
                reader = ExcelUtil.getReader(inputStream);
            } catch (IOException var14) {
                log.error("导入出错：" + var14.getMessage());
                throw new BizException("导入出错：" + var14.getMessage());
            }

            List<Map<String, Object>> readAll = reader.read(1, 1, 100000);
            List<Map<String, Object>> res = new ArrayList();

            HashMap resMap;
            label49:
            for (Iterator var7 = readAll.iterator(); var7.hasNext(); res.add(resMap)) {
                Map<String, Object> oneMap = (Map) var7.next();
                resMap = new HashMap();
                Iterator var10 = oneMap.keySet().iterator();

                while (true) {
                    while (true) {
                        if (!var10.hasNext()) {
                            continue label49;
                        }

                        String key1 = (String) var10.next();
//                        if (key1.trim().startsWith("*") && StringUtils.isEmpty(oneMap.get(key1).toString())) {
//                            throw new BizException(key1 + "列有空值，无法导入!");
//                        }

                        Iterator var12 = headerMap.keySet().iterator();

                        while (var12.hasNext()) {
                            String key2 = (String) var12.next();
                            String s = headerMap.get(key2);
                            key1.equals(s);
                            if (key1.equals(s)) {
                                resMap.put(key2, oneMap.get(key1));
                                break;
                            }
                        }
                    }
                }
            }
            return res;
        }
    }

    public static Boolean isRowNotUnique(List<Map<String, Object>> dataList, String fieldName) {
        Set<Object> set1 = new HashSet();
        Iterator var3 = dataList.iterator();

        while (var3.hasNext()) {
            Map<String, Object> m = (Map) var3.next();
            set1.add(m.get(fieldName));
        }

        return dataList.size() != set1.size() ? true : false;
    }


    public void  exportTemplate(HttpServletResponse response, Long orgId) throws IOException {
        HSSFWorkbook excel = new HSSFWorkbook();
        //创建表的名字
        HSSFSheet sheet = excel.createSheet("导入模板");
        ExcelOutUtil excelUtil = new ExcelOutUtil(excel, sheet);
        excelUtil.createFirstRow(1);
        //单元格样式
        // 创建日期格式
        HSSFCellStyle dateStyle = excel.createCellStyle();
        HSSFDataFormat dateFormat = excel.createDataFormat();
        dateStyle.setDataFormat(dateFormat.getFormat("yyyy年m月d日"));

        excelUtil.createFirstRow(1);
        //设置第一行表头
        HSSFRow row = sheet.createRow(0);
        row.setHeightInPoints(30);//设置行的高度
        List<String> handers = Arrays.asList("手机号", "姓名", "性别", "课程名称", "班级名称", "购买课时", "赠送课时", "已上课时", "请假免扣剩余次数", "应收金额（元）", "实收金额（元）", "支付方式", "经办日期", "课程到期日期", "业绩归属人", "对内备注", "对外备注", "学员创建人", "定价名称");
        for (int i = 0; i < handers.size(); i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellValue(handers.get(i));

        }
        //性别
        List<String> sexDate = Arrays.asList("男", "女", "未知");
        excelUtil.createSelectDateList(sexDate)
                .effectivenessSelectData(2);
        //课程
        QueryWrapper<TCourse> qwc = new QueryWrapper();
        qwc.eq("org_id", orgId);
        qwc.eq("is_delete", "0");
        List<TCourse> list = tCourseService.list(qwc);
        List<Long> cIDs=new ArrayList<>();
        if (list.size() > 0) {
            cIDs=list.stream().map(c -> c.getId()).collect(Collectors.toList());
            List<String> courseDate = list.stream().map(c -> c.getName()).collect(Collectors.toList());
            excelUtil.createSelectDateList(courseDate)
                    .effectivenessSelectData(3);
        }

        //班级
        LambdaQueryWrapper<StudentClass> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StudentClass::getOrgId, orgId);
        wrapper.eq(StudentClass::getDeleted, "0");
        List<StudentClass> classes = classService.list(wrapper);
        if (classes.size() > 0) {
            List<String> classDate = classes.stream().map(c -> c.getName()).collect(Collectors.toList());
            excelUtil.createSelectDateList(classDate)
                    .effectivenessSelectData(4);
        }

        //支付方式
        QueryWrapper<TLabel> qwl = new QueryWrapper<>();
        qwl.eq("org_id", orgId);
        qwl.eq("lable_type", "pay_type");
        List<TLabel> list1 = labelService.list(qwl);
        if (list1.size() > 0) {
            List<String> labelDate = list1.stream().map(c -> c.getName()).collect(Collectors.toList());
            excelUtil.createSelectDateList(labelDate)
                    .effectivenessSelectData(11);
        }

        //经办日期
        excelUtil.setDateFormatValidation(12);
        sheet.setDefaultColumnStyle(12, dateStyle);
        //课程到期日期
        excelUtil.setDateFormatValidation(13);
        sheet.setDefaultColumnStyle(13, dateStyle);

        EmployeeVo employeeVo = new EmployeeVo();
        employeeVo.setOrgId(orgId);
        List<EmployeeVo> employees = emloyeeService.peopleJobList(employeeVo);
        if (employees.size() > 0) {
            List<String> employeeDate = employees.stream().map(c -> c.getNickName()).collect(Collectors.toList());
            //业绩归属人
            excelUtil.createSelectDateList(employeeDate)
                    .effectivenessSelectData(14);
            //创建人
            excelUtil.createSelectDateList(employeeDate)
                    .effectivenessSelectData(17);
        }

        if(cIDs.size()>0) {
            //定价名称
            QueryWrapper<TCoursePrice> qwcp = new QueryWrapper<>();
            qwcp.in("course_id", cIDs);
            qwcp.eq("is_delete", "0");
            List<TCoursePrice> list2 = coursePriceService.list(qwcp);
            if(list2.size()>0){
                List<String> cpDate =list2.stream().map(p->p.getName()).collect(Collectors.toList());
                excelUtil.createSelectDateList(cpDate)
                        .effectivenessSelectData(18);
            }
        }
        response.setContentType("application/octet-stream");//，并根据不同的MIME调用浏览器内不同的程序嵌入模块来处理相应的数据。
        response.flushBuffer();     //flushBuffer()会强行把Buffer的 内容写到客户端浏览器
        response.setHeader("Content-disposition", "模板下载.xls");
        excel.write(response.getOutputStream());
    }


    public void  exportClueTemplate(HttpServletResponse response, Long orgId) throws IOException {
        HSSFWorkbook excel = new HSSFWorkbook();
        //创建表的名字
        HSSFSheet sheet = excel.createSheet("导入模板");
        ExcelOutUtil excelUtil = new ExcelOutUtil(excel, sheet);
        excelUtil.createFirstRow(1);
        //单元格样式
        // 创建日期格式
        HSSFCellStyle dateStyle = excel.createCellStyle();
        HSSFDataFormat dateFormat = excel.createDataFormat();
        dateStyle.setDataFormat(dateFormat.getFormat("yyyy-MM-dd"));

        excelUtil.createFirstRow(1);
        //设置第一行表头
        HSSFRow row = sheet.createRow(0);
        row.setHeightInPoints(30);//设置行的高度
        List<String> handers = Arrays.asList("姓名","性别","手机号","学员来源","出生日期","就读学校","当前年级","学员创建人","创建时间","备注"
        );
        for (int i = 0; i < handers.size(); i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellValue(handers.get(i));

        }
        //性别
        List<String> sexDate = Arrays.asList("男", "女", "未知");
        excelUtil.createSelectDateList(sexDate)
                .effectivenessSelectData(1);

        // 年级
        QueryWrapper<StudentClassGrade> wrapper = new QueryWrapper<>();
        wrapper.eq("deleted",0);
        List<StudentClassGrade> list = classGradeService.list(wrapper);
        if (list.size() > 0) {
            List<String> grades = list.stream().map(c -> c.getName()).collect(Collectors.toList());
            excelUtil.createSelectDateList(grades)
                    .effectivenessSelectData(6);
        }
        // 来源
        List<Student> listSource = studentService.listSource();
        if (list.size() > 0) {
            List<String> source = listSource.stream().map(c -> c.getDictLabel()).collect(Collectors.toList());
            excelUtil.createSelectDateList(source)
                    .effectivenessSelectData(3);
        }

        EmployeeVo employeeVo = new EmployeeVo();
        employeeVo.setOrgId(orgId);
        List<EmployeeVo> employees = emloyeeService.peopleJobList(employeeVo);
        if (employees.size() > 0) {
            List<String> employeeDate = employees.stream().map(c -> c.getNickName()).collect(Collectors.toList());
            //创建人
            excelUtil.createSelectDateList(employeeDate)
                    .effectivenessSelectData(7);
        }
        // 出生时间
        excelUtil.setDateFormatValidation(4);
        sheet.setDefaultColumnStyle(4, dateStyle);
        // 创建时间
        excelUtil.setDateFormatValidation(8);
        sheet.setDefaultColumnStyle(8, dateStyle);

        response.setContentType("application/octet-stream");//，并根据不同的MIME调用浏览器内不同的程序嵌入模块来处理相应的数据。
        response.flushBuffer();     //flushBuffer()会强行把Buffer的 内容写到客户端浏览器
        response.setHeader("Content-disposition", "模板下载.xls");
        excel.write(response.getOutputStream());
    }
}


